package nl.hva.web.mvcwebapp.controllers;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import nl.hva.web.mvcwebapp.doa.CourseDAO;
import nl.hva.web.mvcwebapp.doa.NewsDAO;
import nl.hva.web.mvcwebapp.doa.PageDAO;
import nl.hva.web.mvcwebapp.models.Course;
import nl.hva.web.mvcwebapp.models.News;
import nl.hva.web.mvcwebapp.models.Page;
import nl.hva.web.mvcwebapp.models.PageWidget;
import nl.hva.web.mvcwebapp.models.Widget;
import nl.hva.web.mvcwebapp.service.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class PageController extends HttpServlet {

    private String address = "pages.jsp";
    ArrayList paths_jsp = new ArrayList();
    ArrayList paths = new ArrayList();

    /*
     * HTTP GET request
     */
    public ArrayList getPaths() {
        ArrayList paths = new ArrayList();
        paths.add(0, "/pages");
        paths.add(1, "/pages/save");
        paths.add(2, "/pages/language");
        return paths;
    }

    public ArrayList getPathsJSP() {
        ArrayList paths_jsp = new ArrayList();
        paths_jsp.add(0, "/pages/pages.jsp");
        paths_jsp.add(1, "/pages/pages.jsp");
        paths_jsp.add(2, "/index.jsp");
        return paths_jsp;
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();
        boolean redirect = false;
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        String path = request.getServletPath();


        for (int i = 0; i < paths.size(); i++) {
            try {
                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    // /news
                    if (i == 0) {
                        //Catching Page ID, if nonexistant, give homepage.
                        int pageID = PageDAO.getPageByPath("/index.jsp").getPageId();
                        try {
                            pageID = Integer.parseInt(request.getParameter("id"));
                        } catch (Exception e) {
                        }
                        //Catch if ID is valid, if not, give homepage.
                        if (PageDAO.getPage(pageID) == null) {
                            pageID = PageDAO.getPageByPath("/index.jsp").getPageId();
                        }
                        //Getting the confirmed page and then using it for the rest of the data
                        Page selectedPage = PageDAO.getPage(pageID);
                        String widgetPath = selectedPage.getPagePath();
                        List<Widget> widgetList = PageDAO.getAllWidgets();
                        List<Page> pageList = PageDAO.getAllPages();
                        List<Widget> widgetsByPathArea0 = PageDAO.getWidgetsByPathAndLocId(widgetPath, 0);
                        List<Widget> widgetsByPathArea1 = PageDAO.getWidgetsByPathAndLocId(widgetPath, 1);
                        List<Widget> widgetsByPathArea2 = PageDAO.getWidgetsByPathAndLocId(widgetPath, 2);
                        List<Widget> widgetsByPathArea3 = PageDAO.getWidgetsByPathAndLocId(widgetPath, 3);
                        List<Widget> widgetsByPathArea4 = PageDAO.getWidgetsByPathAndLocId(widgetPath, 4);
                        List<PageWidget> pwlist = PageDAO.getAllPageWidgets();
                        List<Widget> allWidgetsByPath = PageDAO.getWidgetsByPath(widgetPath);
                        tx.commit();

                        request.setAttribute("allWidgets", widgetList);
                        request.setAttribute("allPages", pageList);
                        request.setAttribute("selectedPage", selectedPage);
                        request.setAttribute("pwlist", pwlist);
                        request.setAttribute("allWidgetsByPath", allWidgetsByPath);
                        request.setAttribute("widgetpath", widgetPath);

                        //Debug requests
                        request.setAttribute("widgetsByPathArea0", widgetsByPathArea0);
                        request.setAttribute("widgetsByPathArea1", widgetsByPathArea1);
                        request.setAttribute("widgetsByPathArea2", widgetsByPathArea2);
                        request.setAttribute("widgetsByPathArea3", widgetsByPathArea3);
                        request.setAttribute("widgetsByPathArea4", widgetsByPathArea4);
                    } // new news item
                    else if (i == 1) {
                        PageDAO.autoCreateDefaults();
                    }else if(i == 2){
                        String lang = (String) request.getParameter("lang");
                        HttpSession sessie = request.getSession();
                        if(lang.equals("nl")){
                            sessie.setAttribute("lang", "nl");
                        }else if(lang.equals("en")){
                            sessie.setAttribute("lang", "en");
                        }
                        redirect = true;
                        response.sendRedirect(response.encodeRedirectURL("../index"));
                    }
                    address = paths_jsp.get(i).toString();
                }
            } catch (Exception E) {
            }
        }

        request.setAttribute("path", path);
        if (!redirect) {
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        }
    }

//    public void doPost(HttpServletRequest request, HttpServletResponse response)
//            throws IOException, ServletException {
//        
//        ArrayList paths = getPaths();
//        ArrayList paths_jsp = getPathsJSP();
//        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
//        Transaction tx = session.beginTransaction();
//        News news = getNewsFromRequest(request);
//        session.saveOrUpdate(news);
//        tx.commit();
//        session.close();
//        response.sendRedirect("../news");
//    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        String path = request.getServletPath();
        for (int i = 0; i < paths.size(); i++) {
            try {
                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    address = paths_jsp.get(i).toString();
                    if (i == 0) {
                        // ---------------- SAVE --------------------
                        //First step, creating pagetastic as placeholder.
                        System.out.println("Save");
                        //Grab the current page with the id that has been provided
                        Page pagetastic = PageDAO.getPage(Integer.parseInt(request.getParameter("pageId")));
                        //Updating the page model with the data
                        pagetastic.setPageName(request.getParameter("pageName"));
                        pagetastic.setPageLayout(request.getParameter("pageLayout"));
                        pagetastic.setPageBackground(request.getParameter("pageBackground"));
                        pagetastic.setPageColor(request.getParameter("pageColor"));
                        System.out.println("COLOR IS: "+request.getParameter("pageColor"));
                        //Clearing all existing relations
                        PageDAO.deletePageWidgetOnPage(pagetastic.getPageId());
                        //re-adding the relations based on the input
                        for (int j = 1; j < PageDAO.getAllWidgets().size() + 1; j++) {
                            if (request.getParameter("widget" + j) != null) {
                                try {
                                    pagetastic.addWidget(PageDAO.getWidget(j), Integer.parseInt(request.getParameter("widgetLocation" + j)));
                                    System.out.println(j);
                                } catch (Exception e) {
                                    System.out.println(e.getMessage());
                                }
                            }
                        }
                        PageDAO.updatePage(pagetastic);
                        response.sendRedirect(response.encodeRedirectURL("pages?id=" + pagetastic.getPageId()));

                    }
                    // ---------------- /pages/save --------------------
                    if (i == 1) {

                        System.out.println("dummy");

                        response.sendRedirect(response.encodeRedirectURL("/pages"));

                    }
                }
            } catch (Exception E) {
            }
        }

    }
}
